package com.webservice.impl;

import com.alibaba.fastjson.JSON;
import com.dao.BiddingDao;
import com.dao.EquipmentDao;
import com.dao.Maintenance_orderDao;
import com.dao.UserDao;
import com.domain.*;
import com.tool.Sms;
import com.tool.Until;
import com.webservice.ProcessWebservice;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.util.*;
import java.util.logging.Logger;

@WebService(targetNamespace = "http://39.98.59.6/mmms_test/ws/process")
public class ProcessWebserviceImpl implements ProcessWebservice {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ProcessWebserviceImpl.class);

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private HistoryService historyService;

    @Resource
    private ManagementService managementService;


    @Autowired
    private Maintenance_orderDao maintenance_orderDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    private BiddingDao biddingDao;

    @Autowired
    private Until until;





    private String findApproverTel(Integer order_id){

        Maintenance_order order = maintenance_orderDao.findOneById(order_id);
        User equipment_admin = new User();
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        for (Maintenance_process process:processList){
            if (process.getTask_id() == 1){
                equipment_admin = until.findById(process.getTransactor_id());
                break;
            }
        }
        List<User> approverList = userDao.findApproverByDepartment(order.getDepartment_id());
        String approvers_tel = "";
        String sp1 = "";
        if (approverList!=null){
            for (User user:approverList){
                if (user.getId().equals(equipment_admin.getId())){
                    continue;
                }
                if (user.getTel().length() == 11){
                    approvers_tel = approvers_tel + sp1;
                    approvers_tel = approvers_tel+user.getTel();
                    sp1=",";
                }
            }
        }
        return approvers_tel;

    }
    private void admin(Integer order_id, Integer flag){
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        if (processList!=null){
            for (Maintenance_process maintenanceProcess:processList){
                if (maintenanceProcess.getTask_id() == 1){
                    User equipment_admin = userDao.findById(maintenanceProcess.getTransactor_id());
                    if (equipment_admin.getTel().length() == 11){
                        if (flag == 1){
                            Sms.main(equipment_admin.getTel(), "64987");//您的维修单已被驳回。，发起的设备管理员
                        }
                        else if (flag == 2){
                            Sms.main(equipment_admin.getTel(), "64985");//您的维修单状态有更新，请及时查看。，发起的设备管理员
                        }
                        else if (flag == 3){
                            Sms.main(equipment_admin.getTel(), "64993");//设备无法维修，维修单结束，请进行评价。，发起的设备管理员
                        }
                        else if (flag == 4){
                            Sms.main(equipment_admin.getTel(), "65003");//您有待确认的维修单被撤回，发起的设备管理员
                        }
                    }


                }
            }
        }
    }






    @WebResult(name = "int")
    public int skipNode(@WebParam(name = "order_id") Integer order_id,
                        @WebParam(name = "nodeName")String nodeName,
                        @WebParam(name = "user_id") Integer user_id){
        Task task = Until.findTaskById(order_id);
        if (task != null){
            int i = Until.skipToTargetNode(task, nodeName, user_id.toString());
            if (i == 0){
                return 0;
            }
            else {
                return  -1;
            }
        }
        else {
            return -2;
        }

    }



    /**
     * 完全删除一单
     * 数据库中不留痕
     * @param order_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int delOrder(@WebParam(name = "order_id")Integer order_id){
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        if (maintenance_order == null){
            return -1;
        }
        else {
            List<Task> task = taskService.createTaskQuery()

                    .processInstanceBusinessKey(order_id.toString())
                    .list();
            if (task!=null){
                for (Task task1:task){
                    Until.stopAll(task1.getProcessInstanceId());
                    break;
                }

            }
            maintenance_orderDao.delAdditionalEvaluation(order_id);
            maintenance_orderDao.delEvaluation(order_id);
            maintenance_orderDao.delExpenseDetails(order_id);
            maintenance_orderDao.delBidding(order_id);
            maintenance_orderDao.delProcess(order_id);
            maintenance_orderDao.delRequest(order_id);
            maintenance_orderDao.delOrder(order_id);

            return 0;
        }
    }

    /**
     * 新增方法
     * 结束一单，在数据库中保留
     * @param order_id
     * @param user_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int stopOrder(@WebParam(name = "order_id")Integer order_id,
                         @WebParam(name = "user_id")Integer user_id,
                         @WebParam(name = "reason")String reason){
        if (user_id == 1 && !reason.isEmpty() && reason.equals("维修单超时")){
            return Until.priStopOrder(order_id, user_id, reason, 2);
        }
        else {
            return Until.priStopOrder(order_id, user_id, reason, 1);
        }

    }


    /**
     * 新增方法
     * 查找一个维修单审批流程中已审批的审批员
     * @param order_id
     * @return
     */
    @WebResult(name = "userList")
    public List<User> findReviewFinished(@WebParam(name = "order_id")Integer order_id){
        List<User> userList = new ArrayList<User>();
        Maintenance_order order = maintenance_orderDao.findOneById(order_id);
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        if (processList != null){
            for (Maintenance_process process:processList){
                if (order.getOrder_state() == 4){
                    if (process.getTask_id() == 4){
                        User user = until.findById(process.getTransactor_id());
                        if (user!=null){
                            userList.add(user);
                        }

                    }

                }
                else if (order.getOrder_state() == 7){
                    if (process.getTask_id() == 8){
                        User user = until.findById(process.getTransactor_id());
                        if (user!=null){
                            userList.add(user);
                        }

                    }

                }
                else if (order.getOrder_state() == 12){
                    if (process.getTask_id() == 11){
                        User user = until.findById(process.getTransactor_id());
                        if (user!=null){
                            userList.add(user);
                        }

                    }

                }
            }
        }
        else {
            return null;
        }
        return userList;

    }


    /**
     * 新增方法
     * 查找一个维修单审批流程中未审批的审批员
     * @param order_id
     * @return
     */
    @WebResult(name = "userList")
    public List<User> findReview(@WebParam(name = "order_id")Integer order_id){

        List<String> users_str = new ArrayList<>();
        Task task =  taskService.createTaskQuery()
                .processInstanceBusinessKey(order_id.toString())
                .singleResult();
        logger.info("task的ProcessInstanceId："+task.getProcessInstanceId());
        List<User> users = new ArrayList<>();
        //List<User> users2 = new ArrayList<>();
        if (task.getName().equals("审批员审批")){
//            String taskId = Until.targetLastNode(task,"报修审核");
//            logger.info("taskId:"+taskId);
            List<HistoricVariableInstance> list = historyService
                    .createHistoricVariableInstanceQuery()//创建一个历史的流程变量查询
                    .variableName("reviewerList")
                    .orderByProcessInstanceId()
                    .desc()
                    .list();
            logger.info("list的长度："+list.size());
//            Collections.reverse(list);
            for (HistoricVariableInstance hiv : list){
                logger.info("hiv的id："+hiv.getId());
                logger.info("hiv的ProcessInstanceId："+hiv.getProcessInstanceId());
                if (hiv.getProcessInstanceId().equals(task.getProcessInstanceId())){
                    logger.info("找到了");
                    users_str = (List<String>)hiv.getValue();
                    logger.info("users的长度"+users_str.size());
                    break;
                }
            }
//            users = (List<User>) taskService.getVariableLocal(taskId, "first_reviewers");

            if (users_str != null){
                for (String user_str:users_str){
                    User user = Until.findById(Integer.valueOf(user_str.trim()));
                    if (user != null){
                        users.add(user);
                    }
                }
            }
            List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
            if (processList!=null){
                for (int i = processList.size()-1;i>=0;i--){
                    if (processList.get(i).getTask_id() == 4){
                        User user = Until.findById(processList.get(i).getTransactor_id());
                        users.remove(user);
                    }
                    else {
                        break;
                    }
                }
            }
        }
        if (task.getName().equals("审批员竞单审批")){
            List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
            int k = 0;
            if (processList!=null){
                for (int i = processList.size()-1;i>=0;i--){
                    if (processList.get(i).getTask_id() == 3){
                        k = 1;
                        break;
                    }
                    if (processList.get(i).getTask_id() == 13){
                        k = 2;
                        break;
                    }
                }
            }
            else {
                return new ArrayList<>();
            }
//            String taskId = "";
            if (k == 1){
//                taskId = Until.targetLastNode(task,"竞单完毕并选择公司和审批员");
                List<HistoricVariableInstance> list = historyService
                        .createHistoricVariableInstanceQuery()//创建一个历史的流程变量查询
                        .variableName("reviewerList")
                        .orderByProcessInstanceId()
                        .desc()
                        .list();
//                Collections.reverse(list);
                for (HistoricVariableInstance hiv : list){
                    if (hiv.getProcessInstanceId().equals(task.getProcessInstanceId())){
                        users_str = (List<String>)hiv.getValue();
                        break;
                    }
                }
//                users = (List<User>) taskService.getVariableLocal(taskId, "second_reviewers");
            }
            else if (k == 2){
//                taskId = Until.targetLastNode(task,"审核员选择是否维修");
                List<HistoricVariableInstance> list = historyService
                        .createHistoricVariableInstanceQuery()//创建一个历史的流程变量查询
                        .variableName("reviewerList")
                        .orderByProcessInstanceId()
                        .desc()
                        .list();
//                Collections.reverse(list);
                for (HistoricVariableInstance hiv : list){
                    if (hiv.getProcessInstanceId().equals(task.getProcessInstanceId())){
                        users_str = (List<String>)hiv.getValue();
                        break;
                    }
                }
//                users = (List<User>) taskService.getVariableLocal(taskId, "third_reviewers");
            }
            else{
                return new ArrayList<User>();
            }

            if (users_str!=null){
                for (String user_str:users_str){
                    User user = Until.findById(Integer.valueOf(user_str.trim()));
                    if (user != null){
                        users.add(user);
                    }

                }
            }

            for (int i = processList.size()-1;i>=0;i--){
                if (processList.get(i).getTask_id() == 11){
                    User user = Until.findById(processList.get(i).getTransactor_id());
                    users.remove(user);
                }
                else {
                    break;
                }
            }
        }
        if (task.getName().equals("审批员验收")){
//            String taskId = Until.targetLastNode(task,"审核员验收");
            List<HistoricVariableInstance> list = historyService
                    .createHistoricVariableInstanceQuery()//创建一个历史的流程变量查询
                    .variableName("reviewerList")
                    .orderByProcessInstanceId()
                    .desc()
                    .list();
//            Collections.reverse(list);
            for (HistoricVariableInstance hiv : list){
                if (hiv.getProcessInstanceId().equals(task.getProcessInstanceId())){
                    users_str = (List<String>)hiv.getValue();
                    break;
                }
            }
//            users = (List<User>) taskService.getVariableLocal(taskId, "fourth_reviewers");

            if (users_str!=null){
                for (String user_str:users_str){
                    User user = Until.findById(Integer.valueOf(user_str.trim()));
                    users.add(user);
                }
            }
            List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
            if (processList!=null){
                for (int i = processList.size()-1;i>=0;i--){
                    if (processList.get(i).getTask_id() == 8){
                        User user = Until.findById(processList.get(i).getTransactor_id());
                        users.remove(user);
                    }
                    else {
                        break;
                    }
                }
            }
        }


        return users;
    }

    /**
     * 查询维修单上一个任务详情
     * @param order_id
     * @return
     */
    @WebResult(name = "Maintenance_process")
    @Override
    public Maintenance_process lastTaskName(@WebParam(name = "order_id") Integer order_id){
        Maintenance_process process = new Maintenance_process();
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        if (processList!=null){
            process = processList.get(0);
            for (Maintenance_process maintenance_process:processList){
                int flag = maintenance_process.getFinished_time().compareTo(process.getFinished_time());  //这里按我实体中的开始时间属性进行比较
                if (flag > 0){
                    process = maintenance_process;
                }
            }
        }
        return process;
    }

    //根据用户id和维修单状态查询任务数量
    @WebResult(name = "int")
    @Override
    public int taskNum(@WebParam(name = "user_id") Integer user_id,
                       @WebParam(name = "order_state") Integer order_state) {
        List<Task> taskList = taskService.createTaskQuery()

                .taskAssignee(user_id.toString())
                .list();
        int i = 0;
        if (taskList!=null){
            for (Task task:taskList){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(Integer.valueOf(task.getBusinessKey()));
                if (maintenance_order != null && maintenance_order.getOrder_state().equals(order_state)){
                    if (maintenance_orderDao.findOrderProcess(maintenance_order.getId())!=null){
                        maintenance_order =  until.setOrder(maintenance_order);
                        if (maintenance_order.getCreateTime()!=null ){
                            Date now = new Date(System.currentTimeMillis());
                            if (maintenance_order.getOrderPeriodOfValidity() != 0){
                                long day = (now.getTime()-maintenance_order.getCreateTime().getTime())/(24*60*60*1000);
                                if (day <= maintenance_order.getOrderPeriodOfValidity()){
                                    i++;
                                }
                            }
                            else {
                                i++;
                            }

                        }
                    }
                }
            }
        }


        List<Task> taskList1 = taskService.createTaskQuery()//

                .taskCandidateUser(user_id.toString())//根据候选人查询
                .list();
        if (taskList1!=null){
            for (Task task:taskList1){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(Integer.valueOf(task.getBusinessKey()));
                if (maintenance_order != null && maintenance_order.getOrder_state().equals(order_state)){
                    if (maintenance_orderDao.findOrderProcess(maintenance_order.getId())!=null){
                        maintenance_order =  until.setOrder(maintenance_order);
                        if (maintenance_order.getCreateTime()!=null ){
                            Date now = new Date(System.currentTimeMillis());
                            if (maintenance_order.getOrderPeriodOfValidity() != 0){
                                long day = (now.getTime()-maintenance_order.getCreateTime().getTime())/(24*60*60*1000);
                                if (day <= maintenance_order.getOrderPeriodOfValidity()){
                                    i++;
                                }
                            }
                            else {
                                i++;
                            }

                        }
                    }
                }
            }
        }

        return i;
    }

    /**
     * 新增方法
     * 根据用户id查询所有任务数量
     * 用于桌面角标
     * @param user_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int allTaskNum(@WebParam(name = "user_id") Integer user_id){

        List<Task> taskList = taskService.createTaskQuery()

                .taskAssignee(user_id.toString())
                .list();
        int i = 0;
        if (taskList!=null){
            for (Task task:taskList){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(Integer.valueOf(task.getBusinessKey()));
                if (maintenance_order!=null && maintenance_orderDao.findOrderProcess(maintenance_order.getId())!=null){
                    maintenance_order =  until.setOrder(maintenance_order);
                    if (maintenance_order.getCreateTime()!=null ){
                        Date now = new Date(System.currentTimeMillis());
                        if (maintenance_order.getOrderPeriodOfValidity() != 0){
                            long day = (now.getTime()-maintenance_order.getCreateTime().getTime())/(24*60*60*1000);
                            if (day <= maintenance_order.getOrderPeriodOfValidity()){
                                i++;
                            }
                        }
                        else {
                            i++;
                        }

                    }
                }
            }
        }

        List<Task> taskList1 = taskService.createTaskQuery()//

                .taskCandidateUser(user_id.toString())//根据候选人查询
                .list();
        if (taskList1!=null){
            for (Task task:taskList1){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(Integer.valueOf(task.getBusinessKey()));
                if (maintenance_order!=null && maintenance_orderDao.findOrderProcess(maintenance_order.getId())!=null){
                    maintenance_order =  until.setOrder(maintenance_order);
                    if (maintenance_order.getCreateTime()!=null ){
                        Date now = new Date(System.currentTimeMillis());
                        if (maintenance_order.getOrderPeriodOfValidity() != 0){
                            long day = (now.getTime()-maintenance_order.getCreateTime().getTime())/(24*60*60*1000);
                            if (day <= maintenance_order.getOrderPeriodOfValidity()){
                                i++;
                            }
                        }
                        else {
                            i++;
                        }

                    }
                }
            }
        }

        return i;
    }

    @WebResult(name = "int")
    @Override
    public int bidNum(@WebParam(name = "user_id") Integer user_id) {
        User company = Until.findById(user_id);
        List<Integer> types = new ArrayList<>();
        if (company != null){
            types = userDao.findMaintenanceTypeByCompany(company.getId());
        }
        else {
            return -1;
        }

        if (types!=null){
            for (Integer type:types){
                company.setType_id(type);
            }
        }
        List<Maintenance_order> maintenance_orderList = maintenance_orderDao.findByState(2);
        List<Maintenance_order> maintenance_orderList1 = new ArrayList<Maintenance_order>();
        for (Maintenance_order maintenance_order : maintenance_orderList) {
            Task task = Until.findTaskById(maintenance_order.getId());
            List<User> users = (List<User>) runtimeService.getVariable(task.getExecutionId(),"unit");
            User unit = Until.findById(user_id);
            if ((users != null && users.size() > 0) && !users.contains(unit)){
                continue;
            }
            Bidding bidding = biddingDao.findBiddingByCompany(maintenance_order.getId(), user_id);
            maintenance_order = until.setOrder(maintenance_order);
            List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(maintenance_order.getId());
            if (processList!=null){
                Date bidingTime = new Date();
                Date now = new Date(System.currentTimeMillis());
                for (Maintenance_process process:processList){
                    if (process.getTask_id() == 2){
                        bidingTime = process.getFinished_time();
                    }
                }
                long day = (now.getTime()-bidingTime.getTime())/(24*60*60*1000);
                if (day <= maintenance_order.getBiddingPeriodOfValidity()){
                    if (company.getType_id() == 3){
                        if (bidding == null){
                            maintenance_orderList1.add(maintenance_order);
                        }
                    }
                    else if (company.getType_id() == 1 && maintenance_order.getDepartment_id() == 1){
                        if (bidding == null){
                            maintenance_orderList1.add(maintenance_order);
                        }
                    }
                    else if (company.getType_id() == 2 && maintenance_order.getDepartment_id() == 2){
                        if (bidding == null){
                            maintenance_orderList1.add(maintenance_order);
                        }
                    }
                }
            }
        }
        return maintenance_orderList1.size();
    }

    //查询任务
    @WebResult(name = "orderList")
    @Override
    public List<Maintenance_order> findTask(@WebParam(name = "user_id")Integer user_id) {
        List<Task> taskList = taskService.createTaskQuery()

                .taskAssignee(user_id.toString())
                .list();
        //查询组任务
        List<Task> taskList1 = taskService.createTaskQuery()//

                .taskCandidateUser(user_id.toString())//根据候选人查询
                .list();
        List<Maintenance_order> maintenance_orderList = new ArrayList<Maintenance_order>();
        if (taskList!=null){
            for (Task task:taskList){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(Integer.valueOf(task.getBusinessKey()));
                if (maintenance_order!=null && maintenance_orderDao.findOrderProcess(maintenance_order.getId())!=null){
                    maintenance_order =  until.setOrder(maintenance_order);
                    if (maintenance_order.getCreateTime()!=null ){
                        Date now = new Date(System.currentTimeMillis());
                        if (maintenance_order.getOrderPeriodOfValidity() != 0){
                            long day = (now.getTime()-maintenance_order.getCreateTime().getTime())/(24*60*60*1000);
                            if (day <= maintenance_order.getOrderPeriodOfValidity()){
                                maintenance_orderList.add(maintenance_order);
                            }
                        }
                        else {
                            maintenance_orderList.add(maintenance_order);
                        }

                    }
                }
            }
        }


        if (taskList1!=null){
            for (Task task:taskList1){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(Integer.valueOf(task.getBusinessKey()));
                if (maintenance_order!=null && maintenance_orderDao.findOrderProcess(maintenance_order.getId())!=null){
                    maintenance_order =  until.setOrder(maintenance_order);
                    if (maintenance_order.getCreateTime()!=null){
                        Date now = new Date(System.currentTimeMillis());
                        if (maintenance_order.getOrderPeriodOfValidity() != 0){
                            long day = (now.getTime()-maintenance_order.getCreateTime().getTime())/(24*60*60*1000);
                            if (day <= maintenance_order.getOrderPeriodOfValidity()){
                                maintenance_orderList.add(maintenance_order);
                            }
                        }
                        else {
                            maintenance_orderList.add(maintenance_order);
                        }
                    }

                }
            }
        }

        if (maintenance_orderList.size() > 1){
            maintenance_orderList.sort((o1, o2) -> {
                try {
                    if (o1.getCreateTime() == null || o2.getCreateTime() == null) {
                        return 1;
                    }
                    Date dt1 = o1.getCreateTime();
                    Date dt2 = o2.getCreateTime();

                    if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            });
        }
        return maintenance_orderList;
    }

    //启动流程
    @WebResult(name = "int")
    @Override
    public int start(@WebParam(name = "equipment_admin") User equipment_admin,
                     @WebParam(name = "maintenance_order") Maintenance_order maintenance_order,
                     @WebParam(name = "flag") Integer flag,
                     @WebParam(name = "request")String request) {
        if (equipment_admin == null || maintenance_order == null || equipment_admin.getId() == null || maintenance_order.getEquipment_id() == null){
            return -1;
        }
        if (maintenance_order.getProblem_image() == null && maintenance_order.getProblem_video() == null && maintenance_order.getProblem_word() == null) {
            return -2;
        }
        String sp = "";
        String sp1 = "";
        String approvers = "";
        String approvers_tel = "";
        if (maintenance_order.getDepartment_id() != 3){
            List<User> approverList = new ArrayList<>();
            equipment_admin = Until.findById(equipment_admin.getId());
            if (equipment_admin.getRole_id() == 3){
                approverList = userDao.findApproverByDepartment(equipment_admin.getDepartment_id());
            }
            else {
                approverList = userDao.findApproverByDepartment(maintenance_order.getDepartment_id());
            }
            if (approverList!=null){
                for (User user:approverList){
//                    if (user.getId().equals(equipment_admin.getId())){
////                        continue;
////                    }
                    approvers = approvers + sp;
                    approvers = approvers + user.getId();
                    if (user.getTel().length() == 11){
                        approvers_tel = approvers_tel + sp1;
                        approvers_tel = approvers_tel + user.getTel();
                        sp1=",";
                    }
                    sp = ",";
                }
            }
            else {
                return -3;
            }
        }
        else {
            List<User> approverList = userDao.findApproverByDepartment(1);
            List<User> approverList1 = userDao.findApproverByDepartment(2);
            if (approverList1 != null){
                approverList.addAll(approverList1);
            }
            if (approverList!=null){
                for (User user:approverList){
//                    if (user.getId().equals(equipment_admin.getId())){
//                        continue;
//                    }
                    approvers = approvers + sp;
                    approvers = approvers + user.getId();
                    if (user.getTel().length() == 11){
                        approvers_tel = approvers_tel + sp1;
                        approvers_tel = approvers_tel + user.getTel();
                        sp1=",";
                    }
                    sp = ",";
                }
            }
            else {
                return -3;
            }
        }
        maintenance_order.setOrder_state(1);
        maintenance_order.setOrderPeriodOfValidity(0);
        maintenance_orderDao.addOrder(maintenance_order);
        if (request!=null && !request.equals("")){
            maintenance_orderDao.addRequest(maintenance_order.getId(), equipment_admin.getId(), request);
        }

        Map<String,Object> map=new HashMap<String,Object>();
        map.put("equipment_admin", equipment_admin.getId().toString());
        map.put("approvers", approvers);
        //启动流程

        try {
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("order", maintenance_order.getId().toString(), map);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(Arrays.toString(e.getStackTrace()) + "/n " + maintenance_order.getId());
            Until.delOrder(maintenance_order.getId());
            return -5;
        }


        //设置维修流程表

        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(maintenance_order.getId());
        maintenance_process.setTask_id(1);//设备报修
        maintenance_process.setTransactor_id(equipment_admin.getId());
        maintenance_process.setDetail("发起报修申请");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_orderDao.addProcess(maintenance_process);
        //完成任务
        Task task = Until.findTaskById(maintenance_order.getId());
        if (task!=null){
            try {
                taskService.complete(task.getId());

            } catch (Exception e) {
                e.printStackTrace();
                logger.error(Arrays.toString(e.getStackTrace()) + "/n " + maintenance_order.getId());
                Until.delOrder(maintenance_order.getId());
                return -5;
            }
            int i = Sms.main(approvers_tel, "64983");//您有待审核的维修单，请及时查看。给该部门所有审核员发短信
            if (i == 0 || i == 311){
                return 0;
            }
            else {
                return -5;
            }

        }
        else {
            return -4;
        }

    }

    /**
     * 设备管理员撤销维修单
     * @param order_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int equipmentAdmin_returnTask(@WebParam(name = "order_id")Integer order_id){
        String approverTel = findApproverTel(order_id);
        int i = Until.delOrder(order_id);
        if (i == 0){
            if (approverTel.length() == 11){
                try {
                    Sms.main(approverTel,"64997");//您有一个待审核的维修单被撤回
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -2;
                }
            }
            return 0;

        }
        else {
            return -1;
        }
    }

    /**
     * 新增方法
     * 审核员选择维修方进行预估报价
     * @param order_id
     * @param approver_id 审核员id
     * @param unit_id 选择的维修方id
     * @param approver_request 维修要求（选填）
     * @param second_price 拟定报价（选填）
     * order_state：1->16
     * 完成后task_id：2
     * @return 0：正常
     *          -1：无此维修单
     *          -2：无审核员或指定维修方
     *          -3：无此流程
     *          -4：操作失败
     *          -5：发送短信失败
     */
    @WebResult(name = "int")
    @Override
    public int approveToGetEstimate(@WebParam(name = "order_id")Integer order_id,
                                    @WebParam(name = "approver_id")Integer approver_id,
                                    @WebParam(name = "unit_id") Integer unit_id,
                                    @WebParam(name = "approver_request")String approver_request,
                                    @WebParam(name = "second_price")Float second_price){
        if (order_id == null || maintenance_orderDao.findOneById(order_id) == null){
            return -1;//无此维修单
        }
        if (approver_id == null || userDao.findById(approver_id) == null || userDao.findById(unit_id) == null){
            return -2;//无审核员或指定维修方
        }
        Task task = Until.findTaskById(order_id);
        if (task == null){
            return -3;//无此流程
        }
        Maintenance_order order = maintenance_orderDao.findOneById(order_id);
        order = Until.setOrder(order);
        if (!StringUtils.isEmpty(approver_request)){
            Maintenance_request maintenance_request = maintenance_orderDao.findRequest(order_id, approver_id);
            if (maintenance_request == null){
                maintenance_orderDao.addRequest(order_id, approver_id, approver_request);
            }
            else{
                maintenance_orderDao.updateRequest(order_id, approver_id, approver_request);
            }
        }
        if (second_price != null && second_price != 0){
            order.setSecond_price(second_price);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("approver_choice1", 3);
        map.put("pre_unit", unit_id.toString());
        Maintenance_process process = new Maintenance_process();
        process.setOrder_id(order_id);
        process.setTransactor_id(approver_id);
        process.setDetail(Until.findById(approver_id).getName() + "选择维修方询问价格");
        process.setTask_id(2);
        process.setFinished_time(new Date(System.currentTimeMillis()));
        try {
            taskService.complete(task.getId(),map);
        } catch (Exception e) {
            e.printStackTrace();
            return -4;//操作失败
        }
        order.setOrder_state(16);
        order.setUnit_id(unit_id);
        maintenance_orderDao.updateOrder(order);
        maintenance_orderDao.addProcess(process);

        try {
            int i = Sms.main(Until.findById(unit_id).getTel(), "163382");// 您有新的指派维修单待报价
            if (i == 0 || i == 311){
                return 0;
            }
            else {
                return -5;//发送短信失败
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -5;//发送短信失败
        }
    }

    /**
     * 新增方法
     * 审核员从维修方报价状态撤回到报修审核
     * @param order_id
     * @param approver_id 审核员id
     * order_state：16->1
     * 完成后task_id：2
     * @return  0：正常
     *          -1：无此维修单
     *          -2：无审核员
     *          -3：无此流程
     *          -4：操作失败
     *          -5：短信发送失败
     */
    @WebResult(name = "int")
    @Override
    public int EstimateBackToApprover(@WebParam(name = "order_id")Integer order_id,
                                      @WebParam(name = "approver_id")Integer approver_id){

        if (order_id == null || maintenance_orderDao.findOneById(order_id) == null){
            return -1;//无此维修单
        }
        if (approver_id == null || userDao.findById(approver_id) == null){
            return -2;//无审核员
        }
        Task task = Until.findTaskById(order_id);
        if (task == null){
            return -3;//无此流程
        }
        Maintenance_order order = maintenance_orderDao.findOneById(order_id);
        order.setOrder_state(1);
        Maintenance_process process = new Maintenance_process();
        process.setOrder_id(order_id);
        process.setTransactor_id(approver_id);
        process.setDetail(Until.findById(approver_id).getName()+"撤回待维修方报价操作");
        process.setTask_id(2);
        process.setFinished_time(new Date(System.currentTimeMillis()));
        try {
            Until.skipToTargetNode(task, "usertask2",approver_id.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return -4;//操作失败
        }
        maintenance_orderDao.updateOrder(order);
        maintenance_orderDao.addProcess(process);
        try {
            int i = Sms.main(Until.findById(order.getUnit_id()).getTel(), "163383");//您有待报价的维修单被撤回
            if (i == 0 || i == 311){
                return 0;
            }
            else {
                return -5;//发送短信失败
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -5;//短信发送失败
        }


    }

    /**
     * 新增方法
     * 维修方给出预估报价
     * @param order_id
     * @param estimate_price 预估报价
     * @param expense_details 预估材料清单
     * @return 0：正常
     *        -1：无此维修单
     *        -2：无预估价格或价格小于0
     *        -3：无此流程
     *        -4：操作失败
     *        -5：短信发送失败
     * order_state：16->1
     * 完成后task_id：15
     */
    @WebResult(name = "int")
    @Override
    public int EstimateToApprover(@WebParam(name = "order_id")Integer order_id,
                                  @WebParam(name = "estimate_price")Float estimate_price,
                                  @WebParam(name = "expense_details") String expense_details){

        if (order_id == null || maintenance_orderDao.findOneById(order_id) == null){
            return -1;
        }
        if (estimate_price == null || estimate_price < 0){
            return -2;
        }
        Task task = Until.findTaskById(order_id);
        if (task == null){
            return -3;
        }
        Maintenance_order order = maintenance_orderDao.findOneById(order_id);
        order.setEstimate_price(estimate_price);
        order.setOrder_state(1);
        Maintenance_process process = new Maintenance_process();
        process.setOrder_id(order_id);
        process.setTransactor_id(order.getUnit_id());
        process.setDetail(Until.findById(order.getUnit_id()).getName()+"预估价格");
        process.setTask_id(15);
        process.setFinished_time(new Date(System.currentTimeMillis()));
        if (!StringUtils.isEmpty(expense_details)){
            List<Expense_details> expenseDetails = JSON.parseArray(expense_details, Expense_details.class);
            if (expenseDetails!=null){
                for (Expense_details expense_details1:expenseDetails){
                    maintenance_orderDao.addExpense(expense_details1);
                }
            }
        }
        try {
            taskService.complete(task.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return -4;//操作失败
        }
        maintenance_orderDao.updateOrder(order);
        maintenance_orderDao.addProcess(process);
        try {
            String approverTel = findApproverTel(order_id);
            int i = Sms.main(approverTel,"64983"); //您有待审核的维修单，请及时查看。
            if (i == 0 || i == 311){
                return 0;
            }
            else {
                return -5;//发送短信失败
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -5;//发送短信失败
        }
    }

    /**
     * 审核员选择审批员
     * @param order_id 维修单id
     * @param approver_id 当前审核员
     * @param reviewers 审批员列表，格式为：1,2,3,
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int maintenance_review(@WebParam(name = "order_id")Integer order_id,
                                  @WebParam(name = "approver_id")Integer approver_id,
                                  @WebParam(name = "reviewers")String reviewers,
                                  @WebParam(name = "approver_request")String approver_request,
                                  @WebParam(name = "second_price")Float second_price){
        if (reviewers == null){
            return -4;
        }
        if (reviewers.equals("")){
            return -3;
        }
        if (second_price == null){
            second_price = (float)0.00;
        }
        User approver = until.findById(approver_id);
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);
        taskService.claim(task.getId(), approver.getId().toString());
        List<String> reviewers2 = new ArrayList<>();
        List<User> activitiReviewers = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (!reviewers.equals("")) {
            String reviewersTel = "";
            String[] reviewers1 = reviewers.split(",");
            reviewersTel = Until.findById(Integer.valueOf(reviewers1[0])).getTel();
            for (String reviewerId:reviewers1){
                if (reviewerId!=null && !reviewerId.equals("")){
                    User reviewer = until.findById(Integer.valueOf(reviewerId));
                    activitiReviewers.add(reviewer);
                    reviewers2.add(reviewerId);
                }
            }
            map.put("reviewerList", reviewers2);

//            taskService.setVariableLocal(task.getId(), "first_reviewers", activitiReviewers);
            map.put("approver_choice1", 2);
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(2);//报修审核
            maintenance_process.setTransactor_id(approver_id);
            maintenance_process.setDetail(approver.getName()+"通过审核并交给审批员");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            Maintenance_request maintenance_request = maintenance_orderDao.findRequest(order_id, approver_id);
            if (maintenance_request == null){
                if (approver_request!=null && !approver_request.equals("")){
                    maintenance_orderDao.addRequest(order_id, approver_id, approver_request);
                }
            }
            else{
                maintenance_orderDao.updateRequest(order_id, approver_id, approver_request);
            }
            maintenance_order.setSecond_price(second_price);
            maintenance_order.setOrder_state(4);//报修待审批
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.complete(task.getId(), map);
            if (reviewersTel.length() == 11){
                Sms.main(reviewersTel, "64990");//您有待审批的维修单
            }

        }
        else {
            return -2;
        }

        return 0;

    }

    /**
     * 审核员撤回审批申请
     * @param order_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int approver_returnTask(@WebParam(name = "order_id")Integer order_id,
                                   @WebParam(name = "approver_id")Integer approver_id,
                                   @WebParam(name = "flag")Integer flag){

        Logger logger = Logger.getGlobal();
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        if (processList!=null && processList.size()>0){
            Maintenance_process process = processList.get(processList.size()-1);
            if (process.getTask_id() == 4 || process.getTask_id() == 8 || process.getTask_id() == 11){
                return -3;
            }
        }

        List<User> users =new ArrayList<>();
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(order_id.toString())
                .singleResult();
        if (task!=null){
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User approver = until.findById(approver_id);
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            if (flag == 1){
                maintenance_process.setTask_id(2);//报修审核
            }
            else if (flag == 2){
                maintenance_process.setTask_id(13);//竞单审核
            }
            else if (flag == 3){
                maintenance_process.setTask_id(7);//审核员确认
            }
            else if (flag == 4){
                maintenance_process.setTask_id(3);//正在竞单
            }

            String reviewersTel = "";
            User user = Until.findById(Integer.valueOf(task.getAssignee()));
            reviewersTel = user.getTel();
            maintenance_process.setTransactor_id(approver_id);
            maintenance_process.setDetail(approver.getName()+"撤销申请审批操作");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            if (flag == 1){
                maintenance_order.setOrder_state(1);//报修待审核
                Until.skipToTargetNode(task, "usertask2",approver_id.toString());
            }
            else if (flag == 2){
                maintenance_order.setOrder_state(13);//竞单待审核
                Until.skipToTargetNode(task, "usertask7",approver_id.toString());
            }
            else if (flag == 3){
                maintenance_order.setOrder_state(6);//待审核员确认
                Until.skipToTargetNode(task, "usertask13",approver_id.toString());
            }
            else if (flag == 4){
                maintenance_order.setOrder_state(2);//正在竞单
                Until.skipToTargetNode(task, "usertask4",approver_id.toString());
            }

            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);


            if (reviewersTel.length() == 11){
                Sms.main(reviewersTel, "64998");//您有一个待审批的维修单已撤回
            }

            return 0;
        }
        else {
            return -1;
        }
    }


    /**
     * 审核员撤回竞单或者指派
     * @param order_id
     * @param approver_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int approver_returnUnit(@WebParam(name = "order_id")Integer order_id,
                                   @WebParam(name = "approver_id")Integer approver_id) {
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        String unitTel = "";
        if (maintenance_order.getOrder_state() == 14){
            User unit = until.findById(maintenance_order.getUnit_id());
            unitTel = unit.getTel();
        }
        User approver = until.findById(approver_id);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(2);//报修审核
        maintenance_process.setTransactor_id(approver_id);
        maintenance_process.setDetail(approver.getName()+"撤销操作");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_order.setOrder_state(1);//报修待审核
        Task task = Until.findTaskById(order_id);
        int i = Until.skipToTargetNode(task, "usertask2", approver_id.toString());
        if (i == 0){
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            if (!unitTel.equals("") && unitTel.length() == 11){
                Sms.main(unitTel,"65000");//您有一个被指派的维修单被撤回
            }
        }
        return i;
    }

    //审批员报修审批
    @WebResult(name = "int")
    public int first_review(@WebParam(name = "order_id")Integer order_id,
                            @WebParam(name = "reviewer_id")Integer reviewer_id,
                            @WebParam(name = "review_request")String review_request,
                            @WebParam(name = "reason")String reason){
        if (order_id!=null){
            Task task = Until.findTaskByUserId(order_id, reviewer_id);
            if (task == null){
                return -3;
            }
            List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
            Maintenance_process process = new Maintenance_process();
            if (processList!=null && processList.size()>0){
                for (int i = processList.size()-1;i>=0;i--){
                    if (processList.get(i).getTask_id() == 2){
                        process = processList.get(i);
                        break;
                    }
                }
            }

            User reviewer = until.findById(reviewer_id);
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(4);//报修审批
            maintenance_process.setTransactor_id(reviewer_id);
            if (reason!=null && !reason.equals("")){
                maintenance_process.setDetail(reviewer.getName()+"\t报修审批不同意");
                Until.skipToTargetNode(task, "usertask2", process.getTransactor_id().toString());

            }
            else {
                maintenance_process.setDetail(reviewer.getName()+"\t报修审批同意");
                taskService.complete(task.getId());
            }
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_process.setReason(reason);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            Maintenance_request maintenance_request = maintenance_orderDao.findRequest(order_id, reviewer_id);
            if (maintenance_request == null){
                if (review_request!=null && !review_request.equals("")){
                    maintenance_orderDao.addRequest(order_id, reviewer_id, review_request);
                }

            }
            else {
                maintenance_orderDao.updateRequest(order_id, reviewer_id, review_request);
            }



            maintenance_orderDao.addProcess(maintenance_process);


            Task task1 = taskService.createTaskQuery()
                    .processInstanceBusinessKey(order_id.toString())
                    .singleResult();
            if (task1!=null){
                if (task1.getName().equals("报修审核")){
                    maintenance_order.setOrder_state(1);//报修待审核
                    maintenance_orderDao.updateOrder(maintenance_order);
                    String approverTel = findApproverTel(order_id);
                    Sms.main(approverTel, "64983");//您有待审核的维修单
                }
                else if (task1.getName().equals("审批员审批")){
                    if (!StringUtils.isEmpty(task1.getAssignee()) ){
                        User user = Until.findById(Integer.valueOf(task1.getAssignee()));
                        if (user.getTel().length() == 11){
                            Sms.main(user.getTel(), "64990");//您有待审批的维修单
                        }

                    }
                }
            }
            return 0;
        }
        else {
            return -1;
        }
    }

    //审核员选择竞单
    @WebResult(name = "int")
    @Override
    public int approveOrder_Bid(@WebParam(name = "order_id")Integer order_id,
                                @WebParam(name = "user_id")Integer user_id,
                                @WebParam(name = "biddingPeriodOfValidity") Integer biddingPeriodOfValidity,
                                @WebParam(name = "approver_request")String approver_request,
                                @WebParam(name = "second_price")Float second_price,
                                @WebParam(name = "unit") String unit) {
        if (order_id!=null){
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User approver = userDao.findInsiderById(user_id);
            Task task = Until.findTaskById(order_id);
            taskService.claim(task.getId(), approver.getId().toString());
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("approver_choice1", 1);
            map.put("approver_choice2", 1);
            List<User> users = new ArrayList<>();
            if (task!=null){
                if (!StringUtils.isEmpty(unit)){
                    String[] units = unit.trim().split(",");
                    for (String user:units){
                        User user1 = Until.findById(Integer.valueOf(user));
                        users.add(user1);
                    }
                    runtimeService.setVariable(task.getExecutionId(), "unit", users);
                }
                else {
                    runtimeService.setVariable(task.getExecutionId(), "unit", users);
                }
                Maintenance_process maintenance_process = new Maintenance_process();
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(2);//报修审核
                maintenance_process.setTransactor_id(user_id);
                maintenance_process.setDetail(approver.getName()+"通过审核并选择公司竞单");
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(2);//正在竞单
                maintenance_order.setBiddingPeriodOfValidity(biddingPeriodOfValidity);
                if(approver_request!=null && !approver_request.isEmpty()){
                    Maintenance_request request = maintenance_orderDao.findRequest(maintenance_order.getId(), user_id);
                    if (request!=null){
                        maintenance_orderDao.updateRequest(maintenance_order.getId(), user_id, approver_request);
                    }
                    else {
                        maintenance_orderDao.addRequest(maintenance_order.getId(), user_id, approver_request);
                    }
                }
                if (second_price != null && second_price != 0){
                    maintenance_order.setSecond_price(second_price);
                }
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                taskService.complete(task.getId(), map);
                String sp = "";
                String companys = "";
                for (User user:users){
                    user = until.findById(user.getId());
                    if (user.getTel().length() == 11 && user.getRole_id() == -1){
                        companys = companys + sp;
                        companys = companys + user.getTel();
                        sp = ",";
                    }
                }

                try {
                    Sms.main(companys, "64988");//您有新的维修单了，快来抢啊！给有竞单资格的公司发短信
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -4;
                }

            }
            else {
                return -3;
            }
        }
        else {
            return -1;
        }

    }

    //审核员选择指派
    @WebResult(name = "int")
    @Override
    public int approveOrder_Repair(@WebParam(name = "order_id")Integer order_id,
                                   @WebParam(name = "unit_id")Integer unit_id,
                                   @WebParam(name = "user_id")Integer user_id,
                                   @WebParam(name = "approver_request")String approver_request,
                                   @WebParam(name = "second_price")Float second_price) {
        if (order_id!=null){
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User approver = userDao.findInsiderById(user_id);
            User maintenance_unit = userDao.findById(unit_id);
            Task task = Until.findTaskById(order_id);
            taskService.claim(task.getId(), approver.getId().toString());
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("approver_choice1", 1);
            map.put("approver_choice2", 2);
            if (user_id!=null && unit_id!=null){
                map.put("maintenance_unit", unit_id.toString());
            }
            else {
                return -2;
            }
            if (task!=null){
                Maintenance_process maintenance_process = new Maintenance_process();
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(2);//报修审核
                maintenance_process.setTransactor_id(user_id);
                maintenance_process.setDetail(approver.getName()+"通过审核并指派维修单位为"+maintenance_unit.getName());
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(14);//正在维修
                maintenance_order.setUnit_id(unit_id);
                if(approver_request!=null && !approver_request.isEmpty()){
                    Maintenance_request request = maintenance_orderDao.findRequest(maintenance_order.getId(), user_id);
                    if (request!=null){
                        maintenance_orderDao.updateRequest(maintenance_order.getId(), user_id, approver_request);
                    }
                    else {
                        maintenance_orderDao.addRequest(maintenance_order.getId(), user_id, approver_request);
                    }
                }
                if (second_price != null && second_price != 0){
                    maintenance_order.setSecond_price(second_price);
                }
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                taskService.complete(task.getId(), map);
                if (maintenance_unit.getTel().length() == 11){
                    Sms.main(maintenance_unit.getTel(), "64991");//您有新的派单，请及时查收。给被指派的维修方发短信

                }

            }
            else {
                return -3;
            }
        }
        else {
            return -1;
        }
        return 0;
    }


    /**
     * 新增方法
     * 重新选择维修方
     * @param order_id 维修单id
     * @param unit_id 重新选择的维修方
     * @param user_id 操作人
     * @param reason 理由
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int updateUnit(@WebParam(name = "order_id")Integer order_id,
                          @WebParam(name = "unit_id")Integer unit_id,
                          @WebParam(name = "user_id")Integer user_id,
                          @WebParam(name = "reason")String reason) {
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        String unitTel = "";
        if (maintenance_order.getOrder_state() == 14){
            User unit = until.findById(maintenance_order.getUnit_id());
            unitTel = unit.getTel();
        }
        else {
            return -4;
        }
        User approver = until.findById(user_id);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(2);//报修审核
        maintenance_process.setTransactor_id(user_id);
        maintenance_process.setDetail(approver.getName()+"重新选择维修方");
        maintenance_process.setReason(reason);
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        Task task = Until.findTaskById(order_id);
        taskService.setAssignee(task.getId(), unit_id.toString());
//        taskService.saveTask(task);
        try {
            Sms.main(unitTel,"65000");
        } catch (Exception e) {
            e.printStackTrace();
        }
        maintenance_order.setUnit_id(unit_id);
        User newUnit = until.findById(unit_id);
        maintenance_orderDao.addProcess(maintenance_process);
        maintenance_orderDao.updateOrder(maintenance_order);
        if (newUnit.getTel().length() == 11){
            Sms.main(newUnit.getTel(), "64991");//您有新的派单，请及时查收。给被指派的维修方发短信
        }
//        int i = Until.backProcess(task,1);
//        if (i == 0){
//            if (!unitTel.equals("") && unitTel.length() == 11){
//                Sms.main(unitTel,"65000");//您有一个被指派的维修单被撤回
//            }
//        }
//        Task task1 = Until.findTaskById(order_id);
//        Map<String,Object> map=new HashMap<String,Object>();
//        map.put("approver_choice1", 1);
//        map.put("approver_choice2", 2);
//        if (user_id!=null && unit_id!=null){
//            map.put("maintenance_unit", unit_id.toString());
//        }
//        else {
//            return -2;
//        }
//        if (task1!=null){
//            maintenance_order.setUnit_id(unit_id);
//            User newUnit = until.findById(unit_id);
//            maintenance_orderDao.addProcess(maintenance_process);
//            maintenance_orderDao.updateOrder(maintenance_order);
//            taskService.complete(task1.getId(), map);
//            if (newUnit.getTel().length() == 11){
//                Sms.main(newUnit.getTel(), "64991");//您有新的派单，请及时查收。给被指派的维修方发短信
//
//            }
//
//        }
//        else {
//            return -3;
//        }
        return 0;
    }

    //审核员驳回
    @WebResult(name = "int")
    @Override
    public int approveOrder_Refuse(@WebParam(name = "order_id")Integer order_id,
                                   @WebParam(name = "reason")String reason,
                                   @WebParam(name = "user_id")Integer user_id) {
        if (order_id!=null){
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            maintenance_order= until.setOrder(maintenance_order);
            User approver = userDao.findInsiderById(user_id);
            if (user_id!=null){
                Task task = Until.findTaskById(order_id);
                if (task!=null){
                    Until.stopAll(task.getProcessInstanceId());
                    Maintenance_process maintenance_process = new Maintenance_process();
                    maintenance_process.setOrder_id(order_id);
                    maintenance_process.setTask_id(2);//报修审核
                    maintenance_process.setTransactor_id(user_id);
                    maintenance_process.setDetail(approver.getName()+"驳回");
                    maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                    maintenance_process.setReason(reason);
                    maintenance_order.setOrder_state(11);//异常结束
                    maintenance_orderDao.addProcess(maintenance_process);
                    maintenance_orderDao.updateOrder(maintenance_order);
                    admin(order_id,1);//您的维修单已被驳回

                }
                else {
                    return -3;
                }
            }
            else {
                return -2;
            }

        }
        else {
            return -1;
        }
        return 0;
    }

    //竞单后选择公司
    @WebResult(name = "int")
    @Override
    public int choose_Company(@WebParam(name = "order_id")Integer order_id,
                              @WebParam(name = "unit_id")Integer unit_id,
                              @WebParam(name = "reviewer_id") String reviewer_id,
                              @WebParam(name = "approver_id") Integer approver_id) {
        if (order_id!=null && unit_id!=null && reviewer_id!=null){
            Task task = Until.findTaskById(order_id);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User user = userDao.findById(approver_id);
            List<String> reviewerId = new ArrayList<>();
            List<User> activitiReviewers = new ArrayList<>();
            String reviewersTel = "";
            if (!reviewer_id.equals("")){

                String[] reviewers = reviewer_id.split(",");
                reviewersTel = Until.findById(Integer.valueOf(reviewers[0])).getTel();
                for (String reviewer:reviewers){
                    if (!reviewer.equals("")){
                        User reviewer1 = until.findById(Integer.valueOf(reviewer));
                        reviewerId.add(reviewer);
                        activitiReviewers.add(reviewer1);
                    }
                }
            }
            User unit = userDao.findById(unit_id);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("maintenance_unit", unit_id.toString());
            map.put("reviewerList", reviewerId);
            runtimeService.setVariable(task.getExecutionId(), "second_reviewers", activitiReviewers);
            Maintenance_process maintenance_process = new Maintenance_process();
            if (!reviewer_id.equals("")){
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(3);//选择维修单位
                maintenance_process.setTransactor_id(user.getId());
                maintenance_process.setDetail(user.getName()+"选择维修单位为"+unit.getName()+"并交给审批员进行审批");
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(12);//竞单待审批
                maintenance_order.setUnit_id(unit_id);
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                taskService.claim(task.getId(), approver_id.toString());
                taskService.complete(task.getId(), map);
                if (reviewersTel.length() == 11){
                    Sms.main(reviewersTel, "64990");// 您有待审批的维修单，请及时查看 审批员
                }

            }
            else {
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(3);//选择维修单位
                maintenance_process.setTransactor_id(user.getId());
                maintenance_process.setDetail(user.getName()+"选择维修单位为"+unit.getName());
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(13);//竞单待审核
                maintenance_order.setUnit_id(unit_id);
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                taskService.claim(task.getId(), approver_id.toString());
                taskService.complete(task.getId(), map);
                String unitTel = unit.getTel();
                if (unitTel.length() == 11){
                    Sms.main(unitTel, "64994");// 您的维修单已经中标
                }

            }

        }
        else {
            return -1;
        }
        return 0;
    }

    //竞单后放弃维修
    @WebResult(name = "int")
    @Override
    public int choose_Refuse(@WebParam(name = "order_id")Integer order_id,
                             @WebParam(name = "reason")String reason,
                             @WebParam(name = "approver_id") Integer approver_id) {
        if(order_id!=null && reason!=null){
            Task task = Until.findTaskById(order_id);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User user = userDao.findById(approver_id);
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(3);//选择维修单位
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail(user.getName()+"选择放弃维修");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_process.setReason(reason);
            maintenance_order.setOrder_state(11);//异常结束
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            Until.stopAll(task.getProcessInstanceId());
            admin(order_id,1); //您的维修单已被驳回。，发起的设备管理员
        }
        else {
            return -1;
        }
        return 0;
    }


    //审批员选择修
    @WebResult(name = "int")
    @Override
    public int review_Pass(@WebParam(name = "order_id")Integer order_id,
                           @WebParam(name = "reviewer_id")Integer reviewer_id,
                           @WebParam(name = "reason")String reason) {
        Task task = Until.findTaskByUserId(order_id, reviewer_id);
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        maintenance_order = until.setOrder(maintenance_order);
        if (task == null){
            return -3;
        }
        User user = userDao.findById(Integer.valueOf(task.getAssignee()));
        Maintenance_process maintenance_process = new Maintenance_process();
        Maintenance_process process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(11);//竞单审批
        maintenance_process.setTransactor_id(user.getId());
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        if (processList!=null && processList.size()>0){
            for (int i = processList.size()-1;i>=0;i--){
                if (processList.get(i).getTask_id() == 3||processList.get(i).getTask_id() == 13){
                    process = processList.get(i);
                    break;
                }
            }
        }

        if (reason!=null && !reason.equals("")){
            maintenance_process.setDetail(user.getName()+"\t竞单审批不同意");
            Until.skipToTargetNode(task, "usertask7", process.getTransactor_id().toString());

        }
        else {
            maintenance_process.setDetail(user.getName()+"\t竞单审批同意");
            taskService.complete(task.getId());
        }
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_process.setReason(reason);



        maintenance_orderDao.addProcess(maintenance_process);

        Task task1 = taskService.createTaskQuery()
                .processInstanceBusinessKey(order_id.toString())
                .singleResult();
        if (task1.getName().equals("审核员选择是否维修")){
            maintenance_order.setOrder_state(13);//竞单待审核
            maintenance_orderDao.updateOrder(maintenance_order);
            String approverTel = findApproverTel(order_id);
            Sms.main(approverTel, "64983");//您有待审核的维修单
        }
        else if (task1.getName().equals("审批员竞单审批")){
            if (!StringUtils.isEmpty(task1.getAssignee())){
                User user1 = Until.findById(Integer.valueOf(task1.getAssignee()));
                if (user1.getTel().length() == 11){
                    Sms.main(user.getTel(), "64990");//您有待审批的维修单
                }
            }
        }



        return 0;
    }


    /**
     * 审核员选择审批员
     * @param order_id 维修单id
     * @param approver_id 当前审核员
     * @param reviewers 审批员列表，格式为：1,2,3,
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int approver_review(@WebParam(name = "order_id")Integer order_id,
                                  @WebParam(name = "approver_id")Integer approver_id,
                                  @WebParam(name = "reviewers")String reviewers){
        User approver = until.findById(approver_id);
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);

        List<User> activitiReviewers = new ArrayList<>();
        List<String> reviewers2 = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (!reviewers.equals("")) {
            String reviewersTel = "";
            String[] reviewers1 = reviewers.split(",");
            if (reviewers1 != null){
                reviewersTel = Until.findById(Integer.valueOf(reviewers1[0])).getTel();

                for (String reviewerId:reviewers1){
                    if (reviewerId!=null && !reviewerId.equals("")){
                        User reviewer = until.findById(Integer.valueOf(reviewerId));
                        activitiReviewers.add(reviewer);
                        reviewers2.add(reviewerId);


                    }
                }
            }
            else {
                return -1;
            }
            map.put("reviewerList", reviewers2);
//            taskService.setVariableLocal(task.getId(), "third_reviewers", activitiReviewers);
            map.put("approver_choice3", 2);
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(13);//报修审核
            maintenance_process.setTransactor_id(approver_id);
            maintenance_process.setDetail(approver.getName()+"通过审核并交给审批员");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_order.setOrder_state(12);//报修待审批
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.claim(task.getId(), approver_id.toString());
            taskService.complete(task.getId(), map);
            if (reviewersTel.length() == 11){
                Sms.main(reviewersTel, "64990");//您有待审批的维修单，请及时查看
            }

        }
        else {
            return -2;
        }

        return 0;

    }


    /**
     * 审核员选择重新选择维修公司
     * @param order_id 维修单id
     * @param approver_id 当前审核员
     * @return
     */
    @WebResult(name = "int")
    public int approver_turnBid(@WebParam(name = "order_id")Integer order_id,
                                @WebParam(name = "approver_id")Integer approver_id){
        User approver = until.findById(approver_id);
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);

        Map<String,Object> map = new HashMap<>();
        map.put("approver_choice3", 3);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(13);//报修审核
        maintenance_process.setTransactor_id(approver_id);
        maintenance_process.setDetail(approver.getName()+"重新选择维修公司");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_order.setOrder_state(2);//正在竞单
        maintenance_orderDao.addProcess(maintenance_process);
        maintenance_orderDao.updateOrder(maintenance_order);
        taskService.claim(task.getId(), approver_id.toString());
        taskService.complete(task.getId(), map);
//            Sms.main(reviewersTel, "64988");//您有新的维修单了，快来抢啊！给有竞单资格的公司发短信


        return 0;
    }


    /**
     * 审核员确定进行维修
     * @param order_id
     * @param approver_id
     * order_state：13->14
     * 完成后task_id：13
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int makeSureUnit(@WebParam(name = "order_id")Integer order_id,
                            @WebParam(name = "approver_id")Integer approver_id){

        User approver = until.findById(approver_id);
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);


        Map<String,Object> map = new HashMap<>();
        map.put("approver_choice3", 1);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(13);//报修审核
        maintenance_process.setTransactor_id(approver_id);
        maintenance_process.setDetail(approver.getName()+"选择进行维修");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_order.setOrder_state(14);//报修待审批
        maintenance_orderDao.addProcess(maintenance_process);
        maintenance_orderDao.updateOrder(maintenance_order);
        taskService.claim(task.getId(), approver_id.toString());
        taskService.complete(task.getId(), map);
        User unit = until.findById(maintenance_order.getUnit_id());
        if (unit.getTel().length() == 11){
            Sms.main(unit.getTel(), "64994");//您的维修单已经中标
        }



        return 0;

    }




    /**
     * 审批过后，审核员放弃维修
     * @param order_id
     * @param approver_id
     * @param reason
     * order_state：13->11
     * 完成后task_id：13
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int giveUp(@WebParam(name = "order_id")Integer order_id,
                      @WebParam(name = "approver_id")Integer approver_id,
                      @WebParam(name = "reason")String reason){
        User approver = until.findById(approver_id);
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);
        Map<String,Object> map = new HashMap<>();
        map.put("approver_choice3", 1);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(13);//报修审核
        maintenance_process.setTransactor_id(approver_id);
        maintenance_process.setDetail(approver.getName()+"选择放弃维修");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_order.setOrder_state(11);//异常完成
        Until.stopAll(task.getProcessInstanceId());
        maintenance_orderDao.addProcess(maintenance_process);
        maintenance_orderDao.updateOrder(maintenance_order);
        admin(order_id,1);
        return 0;
    }


    /**
     * 维修方接受维修
     * order_state：14->3
     * 完成后task_id：12
     * @param order_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int maintenanceAcceptDecision(@WebParam(name = "order_id")Integer order_id){
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);
        User unit = until.findById(maintenance_order.getUnit_id());

        Map<String,Object> map = new HashMap<>();
        map.put("unit_choice1", 1);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(12);//报修审核
        maintenance_process.setTransactor_id(unit.getId());
        maintenance_process.setDetail(unit.getName()+"接受维修指派");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_order.setOrder_state(3);//正在维修
        maintenance_orderDao.addProcess(maintenance_process);
        maintenance_orderDao.updateOrder(maintenance_order);
        taskService.complete(task.getId(), map);
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        String approverTel = "";
        for (Maintenance_process process:processList){
            if (process.getTask_id() == 2 || process.getTask_id() == 13){
                User approver = until.findById(process.getTransactor_id());
                approverTel = approver.getTel();
            }
        }
        if (approverTel.length() == 11){
            Sms.main(approverTel, "65001");//维修方已接受维修单
        }



        return 0;
    }

    /**
     * 维修方不接受维修
     * order_state：14->1
     * 完成后task_id：12
     * @param order_id
     * @return
     */
    @WebResult(name = "int")
    public int maintenanceRefuseDecision(@WebParam(name = "order_id")Integer order_id,
                                         @WebParam(name = "reason")String reason){

        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        Task task = Until.findTaskById(order_id);
        User unit = until.findById(maintenance_order.getUnit_id());

        Map<String,Object> map = new HashMap<>();
        map.put("unit_choice1", 2);
        Maintenance_process maintenance_process = new Maintenance_process();
        maintenance_process.setOrder_id(order_id);
        maintenance_process.setTask_id(12);//报修审核
        maintenance_process.setTransactor_id(unit.getId());
        maintenance_process.setDetail(unit.getName()+"拒绝维修指派");
        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
        maintenance_process.setReason(reason);
        maintenance_order.setOrder_state(1);//正在维修
        taskService.complete(task.getId(), map);
        maintenance_orderDao.addProcess(maintenance_process);
        maintenance_orderDao.updateOrder(maintenance_order);
        List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
        String approverTel = "";
        for (Maintenance_process process:processList){
            if (process.getTask_id() == 2 || process.getTask_id() == 13){
                User approver = until.findById(process.getTransactor_id());
                approverTel = approver.getTel();
            }
        }
        if (approverTel.length() == 11){
            Sms.main(approverTel, "65002");//维修方拒绝接受维修单

        }
        return 0;

    }



    //维修情况上传
    @WebResult(name = "int")
    @Override
    public int maintenance_Finished(@WebParam(name = "order_id")Integer order_id,
                                    @WebParam(name = "final_price")Float final_price,
                                    @WebParam(name = "warranty_period")Integer warranty_period,
                                    @WebParam(name = "solution_word_description")String solution_word_description,
                                    @WebParam(name = "solution_image_description")String solution_image_description,
                                    @WebParam(name = "solution_video_description")String solution_video_description,
                                    @WebParam(name = "expense_detailsList")String expense_detailsList) {
        if (order_id!=null){
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            if (final_price!=null){
                maintenance_order.setFinal_price(final_price);
            }
            else {
                return -1;
            }
            if (warranty_period!=null){
                maintenance_order.setWarranty_period(warranty_period);
            }
            else {
                return -3;
            }
            Task task = Until.findTaskById(order_id);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("unit_choice2", 1);
            taskService.complete(task.getId(), map);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Task task1 = Until.findTaskById(order_id);

            User user = userDao.findById(Integer.valueOf(task.getAssignee()));
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(5);//维修情况上传
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail(user.getName()+"维修完成并上传维修情况");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            List<Expense_details> details = maintenance_orderDao.findExpenseDetails(order_id, maintenance_order.getUnit_id());

            if (solution_image_description != null ||
                    solution_video_description != null ||
                    solution_word_description != null){
                if (solution_image_description!=null){
                    maintenance_order.setSolution_image(solution_image_description);
                }
                if (solution_video_description!=null){
                    maintenance_order.setSolution_video(solution_video_description);
                }
                if (solution_word_description!=null){
                    maintenance_order.setSolution_word(solution_word_description);
                }
            }
            else {
                return -4;
            }
            if (details!=null){
                maintenance_orderDao.delExpenseDetailsByUnit(order_id,maintenance_order.getUnit_id());
            }
            if (expense_detailsList != null && !expense_detailsList.isEmpty()){
                List<Expense_details> expenseDetails = JSON.parseArray(expense_detailsList, Expense_details.class);
                boolean flag = true;
                if (final_price == 0){
                    flag = false;
                }
                for (Expense_details expense_details:expenseDetails){
                    expense_details.setOrder_id(order_id);
                    expense_details.setUnit_id(maintenance_order.getUnit_id());
                    maintenance_orderDao.addExpense(expense_details);

                    if (!flag){
                        final_price += expense_details.getConsumable_price() * expense_details.getConsumable_num();
                    }
                }
            }
            maintenance_order.setOrder_state(5);//待管理员确认

            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.complete(task1.getId());
            admin(order_id, 2); //您的维修单状态有更新，请及时查看。 设备管理员
        }
        else {
            return -2;
        }


        return 0;
    }


    /**
     * 维修反馈时添加清单文件
     * @param order_id
     * @param fileName
     * @return
     */
    @WebResult(name = "int")
    public int uploadExpenseFile(@WebParam(name = "order_id")Integer order_id,
                                 @WebParam(name = "fileName")String fileName){

        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        maintenance_order.setExpense_file(fileName);
        maintenance_orderDao.updateOrder(maintenance_order);
        return 0;

    }



    /**
     * 维修方上传维修情况后撤回
     * order_state：5->3
     * 完成后task_id：5
     * @param order_id
     * @return
     */
    @WebResult(name = "int")
    @Override
    public int maintenance_turnBack(@WebParam(name = "order_id")Integer order_id){
        Task task = Until.findTaskById(order_id);
        Maintenance_order order = maintenance_orderDao.findOneById(order_id);
        if (order.getOrder_state() == 5){
            int i = Until.backProcess(task,2);
            if (i == 0){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
                Maintenance_process maintenance_process = new Maintenance_process();
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(5);//维修情况上传
                maintenance_process.setTransactor_id(maintenance_order.getUnit_id());
                maintenance_process.setDetail(maintenance_order.getUnit_name()+"撤回维修完成申请");
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(3);//正在维修
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                admin(order_id, 4);
            }
            return 0;

        }
        return -2;
    }


    //修不好
    @WebResult(name = "int")
    @Override
    public int maintenance_Fault(@WebParam(name = "order_id") Integer order_id,
                                 @WebParam(name = "reason") String reason) {
        if (order_id!=null){
            Task task = Until.findTaskById(order_id);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("unit_choice2", 2);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User user = userDao.findById(Integer.valueOf(task.getAssignee()));
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(5);//维修情况上传
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail(user.getName()+"维修失败并上传原因");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_process.setReason(reason);
            maintenance_order.setOrder_state(8);//待评价
            maintenance_order.setSolution_image("");
            maintenance_order.setSolution_video("");
            maintenance_order.setSolution_word("");
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.complete(task.getId(), map);
            admin(order_id,3);  //设备无法维修，维修单结束，请进行评价。 设备管理员

        }
        else {
            return -1;
        }
        return 0;
    }

    //设备管理员确认通过
    @WebResult(name = "int")
    @Override
    public int equipment_admin_Pass(@WebParam(name = "order_id")Integer order_id) {
        if (order_id!=null){
            Task task = Until.findTaskById(order_id);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("equipment_admin_choice1", 1);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User user = userDao.findById(Integer.valueOf(task.getAssignee()));
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(6);//管理员确认
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail(user.getName()+"通过维修完成申请");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_order.setOrder_state(6);//待审核员确认
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.complete(task.getId(), map);
            String approverTel = findApproverTel(order_id);
            Sms.main(approverTel,"64983"); //您有待审核的维修单，请及时查看。
        }
        else {
            return -1;
        }
        return 0;
    }

    //设备管理员驳回
    @WebResult(name = "int")
    @Override
    public int equipment_admin_Refuse(@WebParam(name = "order_id")Integer order_id,
                                      @WebParam(name = "reason")String reason) {
        if (order_id!=null){
            Task task = Until.findTaskById(order_id);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("equipment_admin_choice1", 2);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            maintenance_order = until.setOrder(maintenance_order);
            User user = userDao.findById(Integer.valueOf(task.getAssignee()));
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(6);//管理员确认
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail(user.getName()+"驳回维修完成申请");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_process.setReason(reason);
            maintenance_order.setOrder_state(3);//正在维修
            maintenance_order.setSolution_word("");
            maintenance_order.setSolution_video("");
            maintenance_order.setSolution_image("");
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.complete(task.getId(), map);
            User unit = userDao.findById(maintenance_order.getUnit_id());
            if (unit.getTel().length() == 11){
                Sms.main(unit.getTel(), "64996");//维修结果不满意，请重新维修。维修方

            }
        }
        else {
            return -1;
        }
        return 0;
    }

    //审核员通过并选择审批员
    @WebResult(name = "int")
    @Override
    public int approver_Pass(@WebParam(name = "order_id")Integer order_id,
                             @WebParam(name = "reviewer_id")String reviewer_id,
                             @WebParam(name = "approver_id")Integer approver_id) {
        if (order_id!=null){
            Task task = Until.findTaskById(order_id);
            Map<String,Object> map=new HashMap<String,Object>();
            if (reviewer_id != null && !reviewer_id.equals("")){
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);

                if (maintenance_order.getOrder_state() == 5){
                    Map<String,Object> map1=new HashMap<String,Object>();
                    map1.put("equipment_admin_choice1", 1);
                    taskService.complete(task.getId(), map1);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    task = Until.findTaskById(order_id);
                }

                map.put("approver_choice4", 2);

                List<User> activitiReviewers = new ArrayList<>();

                User user = userDao.findById(approver_id);
                List<String> reviewers = new ArrayList<>();
                String reviewersTel = "";
                String[] reviewers1 = reviewer_id.split(",");
                reviewersTel = Until.findById(Integer.valueOf(reviewers1[0])).getTel();
                for (String reviewerId:reviewers1){
                    if (reviewerId!=null && !reviewerId.equals("")){
                        User reviewer = until.findById(Integer.valueOf(reviewerId));
                        activitiReviewers.add(reviewer);
                        reviewers.add(reviewerId);

                    }
                }
                map.put("reviewerList", reviewers);
//                taskService.setVariableLocal(task.getId(), "fourth_reviewers", activitiReviewers);
                Maintenance_process maintenance_process = new Maintenance_process();
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(7);//审核员确认
                maintenance_process.setTransactor_id(user.getId());
                maintenance_process.setDetail(user.getName()+"通过维修完成申请并交给审批员审批");
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(7);//待审批员确认
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                taskService.claim(task.getId(), approver_id.toString());
                taskService.complete(task.getId(), map);
                if (reviewersTel.length() == 11){
                    Sms.main(reviewersTel, "64990"); //您有待审批的维修单，请及时查看
                }

            }
            else if (reviewer_id != null){
                map.put("approver_choice4", 1);
                User user = userDao.findById(approver_id);
                Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
                if (maintenance_order.getOrder_state() == 5){
                    Map<String,Object> map1=new HashMap<String,Object>();
                    map1.put("equipment_admin_choice1", 1);
                    taskService.complete(task.getId(), map1);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    task = Until.findTaskById(order_id);
                }
                Maintenance_process maintenance_process = new Maintenance_process();
                maintenance_process.setOrder_id(order_id);
                maintenance_process.setTask_id(7);//审核员确认
                maintenance_process.setTransactor_id(user.getId());
                maintenance_process.setDetail(user.getName()+"通过维修完成申请");
                maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                maintenance_order.setOrder_state(8);//待评价
                maintenance_orderDao.addProcess(maintenance_process);
                maintenance_orderDao.updateOrder(maintenance_order);
                taskService.claim(task.getId(), approver_id.toString());
                taskService.complete(task.getId(), map);
            }

        }
        else {
            return -1;
        }
        return 0;
    }

    //审核员驳回
    @WebResult(name = "int")
    @Override
    public int approver_Refuse(@WebParam(name = "order_id")Integer order_id,
                               @WebParam(name = "reason")String reason,
                               @WebParam(name = "approver_id")Integer approver_id) {
        if (order_id!=null && reason!=null){
            Task task = Until.findTaskById(order_id);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("approver_choice4", 3);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            if (maintenance_order.getOrder_state() == 5){
                Map<String,Object> map1=new HashMap<String,Object>();
                map1.put("equipment_admin_choice1", 1);
                taskService.complete(task.getId(), map1);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                task = Until.findTaskById(order_id);
            }
            maintenance_order = until.setOrder(maintenance_order);
            User user = userDao.findById(approver_id);
            Maintenance_process maintenance_process = new Maintenance_process();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(7);//审核员确认
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail(user.getName()+"驳回维修完成申请");
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_process.setReason(reason);
            maintenance_order.setOrder_state(3);//正在维修
            maintenance_order.setSolution_image("");
            maintenance_order.setSolution_video("");
            maintenance_order.setSolution_word("");
            Equipment equipment = equipmentDao.findOneById(maintenance_order.getEquipment_id());
            if(equipment!=null){
                equipment.setMaintenance_times(equipment.getMaintenance_times() + 1);
                if (equipment.getState_id() == 1){
                    equipment.setState_id(2);
                }
                equipmentDao.updateEquipment(equipment);
            }
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.claim(task.getId(), approver_id.toString());
            taskService.complete(task.getId(), map);
            User unit = userDao.findById(maintenance_order.getUnit_id());
            if (unit.getTel().length() == 11){
                Sms.main(unit.getTel(), "64996");//维修结果不满意，请重新维修。 维修方

            }
        }
        else {
            return -1;
        }
        return 0;
    }



    //审批员验收审批
    @WebResult(name = "int")
    @Override
    public int reviewer_Refuse(@WebParam(name = "order_id")Integer order_id,
                               @WebParam(name = "reviewer_id")Integer reviewer_id,
                               @WebParam(name = "reason")String reason) {
        if (order_id!=null){
            Task task = Until.findTaskByUserId(order_id, reviewer_id);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            maintenance_order = until.setOrder(maintenance_order);
            if (task == null){
                return -3;
            }
            User user = userDao.findById(Integer.valueOf(task.getAssignee()));
            Maintenance_process maintenance_process = new Maintenance_process();
            Maintenance_process process = new Maintenance_process();
            List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(order_id);
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(8);//审批员确认
            maintenance_process.setTransactor_id(user.getId());
            if (processList!=null && processList.size()>0){
                for (int i = processList.size()-1;i>=0;i--){
                    if (processList.get(i).getTask_id() == 7){
                        process = processList.get(i);
                        break;
                    }
                }
            }
            if (reason!=null && !reason.equals("")){
                maintenance_process.setDetail(user.getName()+"\t验收审批不同意");
                Until.skipToTargetNode(task, "usertask13", process.getTransactor_id().toString());
            }
            else {
                maintenance_process.setDetail(user.getName()+"\t验收审批同意");
                taskService.complete(task.getId());
            }
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_process.setReason(reason);
            maintenance_order.setOrder_state(6);//待审核员确认
            maintenance_orderDao.addProcess(maintenance_process);

            Task task1 = taskService.createTaskQuery()
                    .processInstanceBusinessKey(order_id.toString())
                    .singleResult();
            if (task1.getName().equals("审核员验收")){
                maintenance_orderDao.updateOrder(maintenance_order);
                String approverTel = findApproverTel(order_id);
                Sms.main(approverTel, "64983");//您有待审核的维修单
            }
            else if (task1.getName().equals("审批员验收")){
                if (!StringUtils.isEmpty(task1.getAssignee())){
                    User user1 = Until.findById(Integer.valueOf(task1.getAssignee()));
                    Sms.main(user1.getTel(), "64990"); //您有待审批的维修单，请及时查看
                }

            }
        }
        else {
            return -1;
        }

        return 0;
    }

    //评价
    @WebResult(name = "int")
    @Override
    public int evaluation(@WebParam(name = "order_id")Integer order_id,
                          @WebParam(name = "maintenance_time")String maintenance_time,
                          @WebParam(name = "maintenance_qualification")String maintenance_qualification,
                          @WebParam(name = "maintenance_attitude")String maintenance_attitude,
                          @WebParam(name = "detail")String detail) {
        if (order_id!=null){
            if (maintenance_time == null || maintenance_time.isEmpty()){
                maintenance_time = "0";
            }
            if (maintenance_qualification == null || maintenance_qualification.isEmpty()){
                maintenance_qualification = "0";
            }
            if (maintenance_attitude == null || maintenance_attitude.isEmpty()){
                maintenance_attitude = "0";
            }
            if (detail == null || detail.isEmpty()){
                detail = "";
            }
            Task task = Until.findTaskById(order_id);
            Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
            User user = userDao.findById(Integer.valueOf(task.getAssignee()));
            Maintenance_process maintenance_process = new Maintenance_process();
            Evaluation evaluation = new Evaluation();
            maintenance_process.setOrder_id(order_id);
            maintenance_process.setTask_id(9);//维修评价
            maintenance_process.setTransactor_id(user.getId());
            maintenance_process.setDetail("维修速度："+maintenance_time + ";" +
                    "\n维修质量："+maintenance_qualification+ ";" +
                    "\n维修态度："+maintenance_attitude+ ";" +
                    "\n评价："+detail);
            maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
            maintenance_order.setOrder_state(9);//待追评
            evaluation.setOrder_id(order_id);
            evaluation.setMaintenance_time(maintenance_time);
            evaluation.setMaintenance_qualification(maintenance_qualification);
            evaluation.setMaintenance_attitude(maintenance_attitude);
            evaluation.setDetail(detail);
            maintenance_orderDao.addProcess(maintenance_process);
            maintenance_orderDao.addEvaluation(evaluation);
            maintenance_orderDao.updateOrder(maintenance_order);
            taskService.complete(task.getId());

        }
        else {
            return -1;
        }
        return 0;
    }


    /**
     * 查询所有能够追评的维修单
     * @return
     */
    @WebResult(name = "orderList")
    @Override
    public List<Maintenance_order> findAdditionalEvaluationOrder(@WebParam(name = "equipment_admin_id")Integer equipment_admin_id){

        List<Maintenance_order> maintenance_orderList1 = new ArrayList<>();
        List<Maintenance_order> maintenance_orderList = maintenance_orderDao.findByState(9);
        if (maintenance_orderList != null){
            for (Maintenance_order maintenance_order:maintenance_orderList){
                List<Maintenance_process> processList = maintenance_orderDao.findOrderProcess(maintenance_order.getId());
                for (Maintenance_process process:processList){
                    if (process.getTask_id() == 1 && process.getTransactor_id().equals(equipment_admin_id)){
                        maintenance_order = until.setOrder(maintenance_order);
                        maintenance_orderList1.add(maintenance_order);
                        break;
                    }
                }

            }
        }
        return maintenance_orderList1;
    }


    //追评
    @WebResult(name = "int")
    @Override
    public int additionalEvaluation(@WebParam(name = "order_id")Integer order_id,
                                    @WebParam(name = "additional_evaluation")String additional_evaluation) {
        if (order_id!=null && additional_evaluation!=null){
            List<Maintenance_order> orders = maintenance_orderDao.findAllOrder();
            if (orders!=null){
                for (Maintenance_order maintenance_order:orders){
                    if (maintenance_order.getId().equals(order_id)){
                        User user = new User();
                        List<Maintenance_process> maintenance_processList = maintenance_orderDao.findOrderProcess(order_id);
                        for (Maintenance_process maintenance_process:maintenance_processList){
                            if (maintenance_process.getTask_id() == 1){
                                user = until.findById(maintenance_process.getTransactor_id());
                                break;
                            }

                        }
                        Maintenance_process maintenance_process = new Maintenance_process();
                        Additional_evaluation additional_evaluation1 = new Additional_evaluation();
                        maintenance_process.setOrder_id(order_id);
                        maintenance_process.setTask_id(10);//维修追评
                        maintenance_process.setTransactor_id(user.getId());
                        maintenance_process.setDetail("追评："+additional_evaluation);
                        maintenance_process.setFinished_time(new Date(System.currentTimeMillis()));
                        maintenance_order.setOrder_state(9);//待追评
                        additional_evaluation1.setOrder_id(order_id);
                        additional_evaluation1.setAdditional_evaluation(additional_evaluation);
                        maintenance_orderDao.addProcess(maintenance_process);
                        maintenance_orderDao.addAdditionalEvaluation(additional_evaluation1);
                        maintenance_orderDao.updateOrder(maintenance_order);
                        break;
                    }
                }
            }
        }
        else {
            return -1;
        }
        return 0;
    }

    //维修完成
    @WebResult(name = "int")
    @Override
    public int stop(@WebParam(name = "order_id")Integer order_id) {
        Maintenance_order maintenance_order = maintenance_orderDao.findOneById(order_id);
        maintenance_order.setOrder_state(10);//维修完成
        maintenance_orderDao.updateOrder(maintenance_order);
        return 0;
    }
}

